"use client";
import { useLocale } from "next-intl";
import { localeItems, useRouter, usePathname } from '@/lib/i18n/config';
import useSettingStore from "@/lib/store/useSettingStore";

function GetLangData(_locale: string) {
    let res = {}
    {
        localeItems.map(locale => {
            if (locale.code === _locale) {
                res = locale
            }
        })
    }
    return res as any
}

export default function LangSwitcher() {
    const locale = useLocale();
    const router = useRouter();
    const pathname = usePathname();
    const setDefaultLocale = useSettingStore((state) => state.setDefaultLocale);

    const handleChange = (e: any) => {
        setDefaultLocale(e.target.value);
        router.push(pathname, { locale: e.target.value });
    };

    return (
        <div>
            <select
                value={locale}
                onChange={handleChange}
                className="w-[100px] h-8 p-1 rounded border-current"
            >
                <option value={locale} > {GetLangData(locale).name}</option>

                {localeItems.map((item) => {

                    if (item.code === locale) return null
                    return (<option key={item.code} value={item.code}>
                        {item.name}
                    </option>)
                })}
            </select>
        </div>
    );
}
